package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.service.CartService;
import cn.edu.tju.elm.service.FoodService;
import cn.edu.tju.elm.service.BusinessService;
import cn.edu.tju.core.security.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import cn.edu.tju.elm.service.CartItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.model.Business;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@Tag(name = "管理购物车", description = "对购物车内的商品增删改查")
public class CartController {
    @Autowired
    private UserService userService;

    @Autowired
    private CartService cartService;

    @Autowired
    private FoodService foodService;

    @Autowired
    private BusinessService businessService;
//    @Autowired
//    private CartItemService cartItemService;

    @PostMapping("/carts")
    @Operation(summary = "添加商品到购物车", description = "将商品添加到当前用户的购物车")
    public HttpResult<Cart> addCartItem(@Valid @RequestBody Cart cartRequest) {
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            // 验证必要的字段
            if (cartRequest.getFood() == null || cartRequest.getFood().getId() == null) {
                return HttpResult.failure(ResultCodeEnum.FOOD_ID_NULL);
            }

//            if (cartRequest.getFood().getBusiness() == null || cartRequest.getFood().getBusiness().getId() == null) {
//                System.out.println(cartRequest.getFood());
//                return HttpResult.failure(ResultCodeEnum.BUSINESS_ID_NULL);
//            }

            if (cartRequest.getQuantity() == null || cartRequest.getQuantity() <= 0) {
                return HttpResult.failure(ResultCodeEnum.FOOD_QUANTITY_ERROR);
            }

            // 检查商品是否存在
            Optional<Food> foodOptional = foodService.findById(cartRequest.getFood().getId());
            if (!foodOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.FOOD_NOT_FOUND);
            }

            // 检查商家是否存在
            Long businessId=foodService.findById(cartRequest.getFood().getId()).get().getBusiness().getId();
            Optional<Business> businessOptional = businessService.findById(businessId);
            if (!businessOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.BUSINESS_NOT_FOUND);
            }

            // 检查是否已存在相同的商品
            Optional<Cart> existingCartItem = cartService.findByCustomerIdAndFoodId(
                    currentUser.getId(), cartRequest.getFood().getId());

            Cart cartItem;
            if (existingCartItem.isPresent()) {
                // 如果已存在，更新数量
                cartItem = existingCartItem.get();
                cartItem.setQuantity(cartItem.getQuantity() + cartRequest.getQuantity());
                cartItem.setUpdateTime(LocalDateTime.now());
                cartItem.setUpdater(currentUser.getId());
            } else {
                // 如果不存在，创建新的购物车项
                cartItem = new Cart();
                cartItem.setFood(foodOptional.get());
                cartItem.setBusiness(businessOptional.get());
                cartItem.setCustomer(currentUser);
                cartItem.setQuantity(cartRequest.getQuantity());
                cartItem.setCreateTime(LocalDateTime.now());
                cartItem.setUpdateTime(LocalDateTime.now());
                cartItem.setCreator(currentUser.getId());
                cartItem.setUpdater(currentUser.getId());
                cartItem.setDeleted(false);
            }

            // 保存购物车项
            Cart savedCartItem = cartService.save(cartItem);
            return HttpResult.success(savedCartItem);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }

    @DeleteMapping("/carts/{foodId}")
    @Operation(summary = "从购物车中删除商品", description = "从当前用户的购物车中删除指定商品")
    public HttpResult<String> removeCartItem(@PathVariable Long foodId) {
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            // 检查购物车项是否存在,findByCustomerIdAndFoodId保证有权删除
            Optional<Cart> cartItemOptional = cartService.findByCustomerIdAndFoodId(
                    currentUser.getId(), foodId);

            if (!cartItemOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.CART_ITEM_NOT_FOUND);
            }

            // 删除购物车项
            cartService.deleteById(cartItemOptional.get().getId());

            return HttpResult.success("商品已从购物车中删除");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }

    @GetMapping("/carts")
    @Operation(summary = "获取购物车列表", description = "获取当前用户的购物车列表")
    public HttpResult<List<Cart>> getCartItems() {
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            // 获取用户的购物车项列表
            List<Cart> cartItems = cartService.findByCustomerId(currentUser.getId());

            return HttpResult.success(cartItems);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR);
        }
    }


    @PutMapping("/carts/{foodId}")
    @Operation(summary = "修改购物车商品数量", description = "修改当前用户购物车中指定商品的数量")
    public HttpResult<Cart> updateCartItemQuantity(
            @PathVariable Long foodId,
            @RequestBody Map<String, Integer> request) {
        try {
            // 获取当前登录用户
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser == null) {
                return HttpResult.failure(ResultCodeEnum.NOT_LOGGED_IN);
            }

            // 验证请求参数
            if (request == null || !request.containsKey("quantity")) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "缺少数量参数");
            }

            Integer quantity = request.get("quantity");

            // 验证数量
            if (quantity == null || quantity < 0) {
                return HttpResult.failure(ResultCodeEnum.FOOD_QUANTITY_ERROR, "商品数量必须大于等于0");
            }

            // 检查购物车项是否存在
            Optional<Cart> cartItemOptional = cartService.findByCustomerIdAndFoodId(
                    currentUser.getId(), foodId);

            if (!cartItemOptional.isPresent()) {
                return HttpResult.failure(ResultCodeEnum.CART_ITEM_NOT_FOUND, "购物车中未找到该商品");
            }

            Cart cartItem = cartItemOptional.get();

            // 如果数量为0，则删除该商品
            if (quantity == 0) {
                cartService.deleteById(cartItem.getId());
                return HttpResult.success();
            }

            // 更新数量
            cartItem.setQuantity(quantity);
            cartItem.setUpdateTime(LocalDateTime.now());
            cartItem.setUpdater(currentUser.getId());

            // 保存更新
            Cart updatedCartItem = cartService.save(cartItem);
            return HttpResult.success(updatedCartItem);

        } catch (Exception e) {
            e.printStackTrace(); // 添加日志输出
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "修改购物车商品数量失败: " + e.getMessage());
        }
    }

}